<template>
    <div class="address-book-settings">
        <pageTitle :title="'通訊錄字段設置'" />

        <div class="settings-container">
            <!-- 左側字段設置 -->
            <div class="fields-settings">
                <div class="settings-header">
                    <el-button type="primary" @click="saveSettings" :loading="saving">
                        <el-icon>
                            <Check />
                        </el-icon>
                        <span>保存設置</span>
                    </el-button>
                    <el-button @click="resetToDefault">恢復默認</el-button>
                </div>

                <el-table :data="fields" style="width: 100%" row-key="id" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" :selectable="selectable" />
                    <el-table-column prop="name" label="字段名稱" width="150" />
                    <el-table-column label="可展示" width="100" align="center">
                        <template #default="{ row }">
                            <el-checkbox v-model="row.visible" :disabled="row.isSystem" />
                        </template>
                    </el-table-column>
                    <el-table-column label="可修改" width="100" align="center">
                        <template #default="{ row }">
                            <el-checkbox v-model="row.editable" :disabled="row.isSystem || !row.visible" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="source" label="字段來源" width="120">
                        <template #default="{ row }">
                            <el-tag :type="row.isSystem ? 'info' : 'success'" size="small">
                                {{ row.isSystem ? '系統自帶' : '自定義' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="排序" width="120" align="center">
                        <template #default="{ row }">
                            <el-icon class="drag-handle" :size="16">
                                <Rank />
                            </el-icon>
                            <span class="sort-number">{{ row.sortOrder }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120" align="center" v-if="hasCustomFields">
                        <template #default="{ row }">
                            <el-button v-if="!row.isSystem" type="danger" size="small" @click="deleteField(row)">
                                刪除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="add-field-form">
                    <el-input v-model="newFieldName" placeholder="輸入新字段名稱" style="width: 200px; margin-right: 10px" />
                    <el-button type="primary" @click="addField" :disabled="!newFieldName">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>添加字段</span>
                    </el-button>
                </div>
            </div>

            <!-- 右側手機預覽 -->
            <div class="mobile-preview">
                <div class="phone-mockup">
                    <div class="phone-header">
                        <span class="back-button">←</span>
                        <span class="title">員工資料</span>
                    </div>
                    <div class="contact-card">
                        <div class="contact-avatar">
                            <el-avatar :size="60" :src="demoUser.avatar" />
                        </div>
                        <div class="contact-name">{{ demoUser.name }}</div>
                        <div class="contact-position">{{ demoUser.position }}</div>

                        <!-- 修改后的 contact-fields 部分 -->
                        <div class="contact-fields">
                            <div class="field-item" v-for="field in visibleFields" :key="field.id">
                                <div class="field-row">
                                    <span class="field-label">{{ field.name }}：</span>
                                    <div class="field-value">
                                        <!-- <template v-if="field.editable">
                                            <el-input v-model="demoUser.fields[field.id]" size="small"
                                                :placeholder="`輸入${field.name}`" />
                                        </template>
                                        <template v-else>
                                            {{ demoUser.fields[field.id] || '無' }}
                                        </template> -->
                                        {{ demoUser.fields[field.id] }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Plus, Rank } from '@element-plus/icons-vue'
import Sortable from 'sortablejs'
import pageTitle from "@/components/pageTitle/pageTitle.vue"

// 表單引用
// const formRef = ref(null)

// 狀態管理
const saving = ref(false)
const newFieldName = ref('')
const selectedFields = ref([])

// 字段數據
const fields = ref([
    { id: 'name', name: '姓名', visible: true, editable: false, isSystem: true, sortOrder: 1 },
    { id: 'avatar', name: '頭像', visible: true, editable: false, isSystem: true, sortOrder: 2 },
    { id: 'mobile', name: '手機號', visible: true, editable: true, isSystem: true, sortOrder: 3 },
    { id: 'email', name: '電子郵件', visible: true, editable: true, isSystem: true, sortOrder: 4 },
    { id: 'position', name: '職位', visible: true, editable: true, isSystem: true, sortOrder: 5 },
    { id: 'department', name: '部門', visible: true, editable: true, isSystem: true, sortOrder: 6 },
    { id: 'company', name: '公司', visible: true, editable: true, isSystem: true, sortOrder: 7 },
    { id: 'address', name: '地址', visible: false, editable: true, isSystem: true, sortOrder: 8 },
    { id: 'birthday', name: '生日', visible: false, editable: true, isSystem: true, sortOrder: 9 },
    { id: 'gender', name: '性別', visible: false, editable: true, isSystem: true, sortOrder: 10 },
])

// 演示用戶數據
const demoUser = ref({
    name: '張三',
    position: '前端工程師',
    avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
    fields: {
        mobile: '13800138000',
        email: 'zhangsan@example.com',
        department: '技術部',
        company: '某某科技有限公司',
        address: '北京市海淀區',
        birthday: '1990-01-01',
        gender: '男'
    }
})

// 計算屬性
const visibleFields = computed(() => {
    return fields.value
        .filter(field => field.visible)
        .sort((a, b) => a.sortOrder - b.sortOrder)
})

const hasCustomFields = computed(() => {
    return fields.value.some(field => !field.isSystem)
})

// 生命週期
onMounted(() => {
    initSortable()
})

// 方法
const handleSelectionChange = (selection) => {
    selectedFields.value = selection
}

const selectable = (row) => {
    return !row.isSystem
}

const addField = () => {
    const newId = `custom_${Date.now()}`
    fields.value.push({
        id: newId,
        name: newFieldName.value,
        visible: true,
        editable: true,
        isSystem: false,
        sortOrder: fields.value.length + 1
    })
    newFieldName.value = ''
    demoUser.value.fields[newId] = ''
    ElMessage.success('字段添加成功')
}

const deleteField = (row) => {
    ElMessageBox.confirm(`確定要刪除字段「${row.name}」嗎?`, '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        fields.value = fields.value.filter(field => field.id !== row.id)
        delete demoUser.value.fields[row.id]
        ElMessage.success('字段刪除成功')
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const saveSettings = () => {
    saving.value = true
    // 模擬API請求
    setTimeout(() => {
        ElMessage.success('設置保存成功')
        saving.value = false
    }, 800)
}

const resetToDefault = () => {
    ElMessageBox.confirm('確定要恢復默認設置嗎? 所有自定義字段將被刪除。', '提示', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        fields.value = fields.value.filter(field => field.isSystem)
        // 重置系統字段的默認值
        fields.value.forEach(field => {
            field.visible = [1, 2, 3, 4, 5, 6, 7].includes(field.sortOrder)
            field.editable = ![1, 2].includes(field.sortOrder)
        })
        ElMessage.success('已恢復默認設置')
    }).catch(() => {
        ElMessage.info('已取消操作')
    })
}

const initSortable = () => {
    const table = document.querySelector('.fields-settings .el-table__body-wrapper tbody')

    Sortable.create(table, {
        animation: 150,
        handle: '.drag-handle',
        onEnd: ({ newIndex, oldIndex }) => {
            if (newIndex !== oldIndex) {
                const movedItem = fields.value.splice(oldIndex, 1)[0]
                fields.value.splice(newIndex, 0, movedItem)

                // 更新排序序號
                fields.value.forEach((item, index) => {
                    item.sortOrder = index + 1
                })
            }
        }
    })
}
</script>

<style scoped lang="less">
.address-book-settings {
    padding: 20px;
    background-color: #fff;

    .settings-container {
        display: flex;
        gap: 20px;
        margin-top: 20px;

        .fields-settings {
            flex: 1;
            padding: 16px;
            border: 1px solid #ebeef5;
            border-radius: 8px;
            background-color: #fff;

            .settings-header {
                display: flex;
                justify-content: space-between;
                margin-bottom: 16px;
            }

            .drag-handle {
                cursor: move;
                color: var(--el-color-primary);
                vertical-align: middle;
            }

            .sort-number {
                margin-left: 5px;
                color: var(--el-text-color-secondary);
            }

            .add-field-form {
                margin-top: 20px;
                display: flex;
                align-items: center;
            }
        }

        .mobile-preview {
            width: 320px;
            position: sticky;
            top: 20px;
            height: fit-content;

            .phone-mockup {
                border: 12px solid #333;
                border-radius: 30px;
                background-color: #f5f5f5;
                height: 600px;
                position: relative;
                overflow: hidden;

                .phone-header {
                    height: 50px;
                    background-color: #fff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-bottom: 1px solid #eee;
                    position: relative;

                    .back-button {
                        position: absolute;
                        left: 15px;
                        font-size: 20px;
                    }

                    .title {
                        font-weight: bold;
                    }
                }

                .contact-card {
                    padding: 20px;
                    text-align: center;

                    .contact-avatar {
                        margin-bottom: 15px;
                    }

                    .contact-name {
                        font-size: 18px;
                        font-weight: bold;
                        margin-bottom: 5px;
                    }

                    .contact-position {
                        color: var(--el-text-color-secondary);
                        margin-bottom: 20px;
                    }

                    .contact-fields {
                        max-height: 400px;
                        overflow-y: auto;
                        padding: 0 10px;

                        .field-item {
                            margin-bottom: 12px;

                            .field-row {
                                display: flex;
                                align-items: center;
                                gap: 8px;

                                .field-label {
                                    flex-shrink: 0;
                                    color: var(--el-text-color-secondary);
                                    font-size: 14px;
                                    width: 70px;
                                    text-align: left;
                                }

                                .field-value {
                                    flex: 1;
                                    font-size: 12px;
                                    word-break: break-word;
                                    text-align: left;

                                    :deep(.el-input) {
                                        width: 100%;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>